package org.xxpay.agent.settlement.ctrl;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.xxpay.agent.common.ctrl.BaseController;
import org.xxpay.core.common.annotation.MethodLog;
import org.xxpay.core.common.constant.Constant;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.constant.RetEnum;
import org.xxpay.core.common.domain.BizResponse;
import org.xxpay.core.common.domain.XxPayPageRes;
import org.xxpay.core.common.domain.XxPayResponse;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.SettBankAccount;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: xiaoyu
 * @date: 2019年5月24日10:20:58
 * @description:
 */
@RestController
@RequestMapping(Constant.AGENT_CONTROLLER_ROOT_PATH + "/bank_account")
@PreAuthorize("hasRole('"+ MchConstant.AGENT_ROLE_NORMAL+"')")
public class BankAccountController extends BaseController {

    private static final MyLog _log = MyLog.getLog(BankAccountController.class);

    /**
     * 添加银行账户信息
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    @MethodLog( remark = "添加结算账户" )
    public ResponseEntity<?> add(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        SettBankAccount agentBankAccount = getObject(param, SettBankAccount.class);
        if(agentBankAccount != null) {
            agentBankAccount.setInfoId(getUser().getId());
            agentBankAccount.setName(getUser().getName());
            agentBankAccount.setInfoType(MchConstant.ACCOUNT_STATUS_AGENT);
        }
        // 判断账号是否被使用
        Long infoId = agentBankAccount.getInfoId();
        String accountNo = agentBankAccount.getAccountNo();
        if(commonService.settBankAccountService.findByInfoIdAndAccountNo(infoId, accountNo) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_AGENT_BANK_ACCOUNTNO_USED));
        }
        // 如果是默认,先将其他都修改为非默认
        if(agentBankAccount.getIsDefault() == 1) {
            SettBankAccount updateAgentBankAccount = new SettBankAccount();
            updateAgentBankAccount.setInfoId(getUser().getId());
            updateAgentBankAccount.setIsDefault(MchConstant.PUB_NO);
            commonService.settBankAccountService.updateByMchId(updateAgentBankAccount, getUser().getId());
        }
        int count = commonService.settBankAccountService.add(agentBankAccount);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    /**
     * 查询列表
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<?> list(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        SettBankAccount agentBankAccount = getObject(param, SettBankAccount.class);
        if(agentBankAccount == null) agentBankAccount = new SettBankAccount();
        agentBankAccount.setInfoId(getUser().getId());
        int count = commonService.settBankAccountService.count(agentBankAccount);
        if(count == 0) return ResponseEntity.ok(XxPayPageRes.buildSuccess());
        List<SettBankAccount> agentAccountHistoryList = commonService.settBankAccountService
                .select((getPageIndex(param)-1) * getPageSize(param), getPageSize(param), agentBankAccount);
        return ResponseEntity.ok(XxPayPageRes.buildSuccess(agentAccountHistoryList, count));
    }

    /**
     * 修改银行账户信息
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    @MethodLog( remark = "修改结算账户" )
    public ResponseEntity<?> update(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        SettBankAccount agentBankAccount = getObject(param, SettBankAccount.class);
        if(agentBankAccount != null) agentBankAccount.setInfoId(getUser().getId());
        // 判断账号是否被使用
        Long infoId = agentBankAccount.getInfoId();
        String accountNo = agentBankAccount.getAccountNo();
        SettBankAccount queryAgentBankAccount = commonService.settBankAccountService.findById(agentBankAccount.getId());

        //添加越权判断
        if(!getUser().getId().equals(queryAgentBankAccount.getInfoId())){
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }

        if(!queryAgentBankAccount.getAccountNo().equals(accountNo) && commonService.settBankAccountService.findByInfoIdAndAccountNo(infoId, accountNo) != null) {
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_AGENT_BANK_ACCOUNTNO_USED));
        }

        // 如果是默认,先将其他都修改为非默认
        if(agentBankAccount.getIsDefault() == 1) {
            SettBankAccount updateAgentBankAccount = new SettBankAccount();
            updateAgentBankAccount.setInfoId(getUser().getId());
            updateAgentBankAccount.setIsDefault(MchConstant.PUB_NO);
            commonService.settBankAccountService.updateByMchId(updateAgentBankAccount, getUser().getId());
        }
        int count = commonService.settBankAccountService.update(agentBankAccount);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    /**
     * 删除银行账户信息
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    @MethodLog( remark = "删除结算账户" )
    public ResponseEntity<?> delete(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");

        //添加越权判断
        SettBankAccount dbRecord = commonService.settBankAccountService.findById(id);
        if(!this.getUser().getId().equals(dbRecord.getInfoId())){
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }

        int count = commonService.settBankAccountService.delete(id);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    /**
     * 查询
     * @return
     */
    @RequestMapping("/get")
    @ResponseBody
    public ResponseEntity<?> get(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");
        SettBankAccount agentBankAccount = new SettBankAccount();
        agentBankAccount.setInfoId(getUser().getId());
        agentBankAccount.setId(id);
        agentBankAccount = commonService.settBankAccountService.find(agentBankAccount);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentBankAccount));
    }

    /**
     * 查询默认账号
     * @return
     */
    @RequestMapping("/default_get")
    @ResponseBody
    public ResponseEntity<?> defaultAccount(HttpServletRequest request) {
        SettBankAccount agentBankAccount = new SettBankAccount();
        agentBankAccount.setInfoId(getUser().getId());
        agentBankAccount.setIsDefault(MchConstant.PUB_YES);
        agentBankAccount = commonService.settBankAccountService.find(agentBankAccount);
        return ResponseEntity.ok(XxPayResponse.buildSuccess(agentBankAccount));
    }

    /**
     * 设置默认账号
     * @return
     */
    @RequestMapping("/default_set")
    @ResponseBody
    @MethodLog( remark = "设置默认结算账户" )
    public ResponseEntity<?> setDefault(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");

        //添加越权判断
        SettBankAccount dbRecord = commonService.settBankAccountService.findById(id);
        if(!this.getUser().getId().equals(dbRecord.getInfoId())){
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }

        // 设置所有状态为非默认
        SettBankAccount agentBankAccount = new SettBankAccount();
        agentBankAccount.setInfoId(getUser().getId());
        agentBankAccount.setIsDefault(MchConstant.PUB_NO);
        int count = commonService.settBankAccountService.update(agentBankAccount);
        _log.info("set all bankAccount default is no, id={}, result={}", id, count);
        // 设置当前为默认
        SettBankAccount agentBankAccount2 = new SettBankAccount();
        agentBankAccount2.setId(id);
        agentBankAccount2.setIsDefault(MchConstant.PUB_YES);
        count = commonService.settBankAccountService.update(agentBankAccount2);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

    /**
     * 取消默认账号
     * @return
     */
    @RequestMapping("/default_cancel")
    @ResponseBody
    @MethodLog( remark = "取消默认结算账户" )
    public ResponseEntity<?> cancelDefault(HttpServletRequest request) {
        JSONObject param = getJsonParam(request);
        Long id = getLongRequired(param, "id");

        //添加越权判断
        SettBankAccount dbRecord = commonService.settBankAccountService.findById(id);
        if(!this.getUser().getId().equals(dbRecord.getInfoId())){
            return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
        }

        // 设置当前为非默认
        SettBankAccount agentBankAccount = new SettBankAccount();
        agentBankAccount.setId(id);
        agentBankAccount.setIsDefault(MchConstant.PUB_NO);
        int count = commonService.settBankAccountService.update(agentBankAccount);
        if(count == 1) return ResponseEntity.ok(BizResponse.buildSuccess());
        return ResponseEntity.ok(BizResponse.build(RetEnum.RET_COMM_OPERATION_FAIL));
    }

}
